package com.fancy.learncenter.ui.fragment;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.czt.mp3recorder.MP3Recorder;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonStudentSubjectiveDataBean;
import com.fancy.learncenter.bean.CartoonSubmitDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.EveryDayWorkActivity;
import com.fancy.learncenter.utils.DataUtil;
import com.fancy.learncenter.utils.FileUtils;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.utils.FileUtils.getEveryDayRecorderAudioPath;

public class CartoonPicSpeakFragment extends BaseFragment {
    //    public static String playUrl = "http://img1.fancyedu.com/show_manage/audio/story/%5B%E5%A5%97%5D%E8%80%81%E6%95%85%E4%BA%8B-%E5%90%8E%E7%BE%BF%E5%B0%84%E6%97%A5.mp3";
    MAudioPlayer audioPlayer;
    String coverImg = "";
    String content = "";
    String playUrl = "";
    View rootView;
    String cachDir;
    String resId;
    String questionsName;
    List<CartoonStudentSubjectiveDataBean.StemsListBean> stemsList;

    //================
    @Bind(R.id.record_audio)
    SimpleDraweeView recordAudio;
    @Bind(R.id.play_record)
    SimpleDraweeView playRecord;
    @Bind(R.id.simpleDraweeView)
    SimpleDraweeView simpleDraweeView;
    @Bind(R.id.textContent)
    TextView textContent;
    @Bind(R.id.complete_tv)
    TextView completeTv;
    @Bind(R.id.total_tv)
    TextView totalTv;

    public CartoonPicSpeakFragment() {

    }

    public static CartoonPicSpeakFragment newInstance(String resId, String questionsName, String speakingPackageId, String cachDir, ArrayList<CartoonStudentSubjectiveDataBean.StemsListBean> stemsList) {

        Bundle args = new Bundle();
        args.putString("resId", resId);
        args.putString("questionsName", questionsName);
        args.putString("speakingPackageId", speakingPackageId);
        args.putString("cachDir", cachDir);
        args.putParcelableArrayList("stemsList", stemsList);

        CartoonPicSpeakFragment fragment = new CartoonPicSpeakFragment();
        fragment.setArguments(args);

        return fragment;
    }

    public static CartoonPicSpeakFragment newInstance(String resId) {

        Bundle args = new Bundle();
        args.putString("resId", resId);
        CartoonPicSpeakFragment fragment = new CartoonPicSpeakFragment();
        fragment.setArguments(args);

        return fragment;
    }


    public static CartoonPicSpeakFragment newInstance(boolean isRealease, boolean isLocal, String filePath, ArrayList<CartoonStudentSubjectiveDataBean.StemsListBean> stemsList) {

        Bundle args = new Bundle();


        if (isRealease) {
            args.putString("isRealease", "0");
        } else {
            args.putString("isRealease", "1");
        }

        if (isLocal) {
            args.putString("isLocal", "0");
        } else {
            args.putString("isLocal", "1");
        }

        args.putString("filePath", filePath);

        args.putParcelableArrayList("stemsList", stemsList);

        CartoonPicSpeakFragment fragment = new CartoonPicSpeakFragment();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            this.cachDir = getArguments().getString("cachDir");
            this.resId = getArguments().getString("resId");
            this.stemsList = getArguments().getParcelableArrayList("stemsList");

            this.speakingPackageId = getArguments().getString("speakingPackageId");
            this.questionsName = getArguments().getString("questionsName");


            if (getArguments().getString("isRealease") != null) {

                if (getArguments().getString("isRealease").equals("0")) {

                    this.isRealease = true;

                } else {

                    this.isRealease = false;

                }

                if (getArguments().getString("isLocal").equals("0")) {

                    this.isLocal = true;

                } else {

                    this.isLocal = false;

                }

                this.realeaseList = getArguments().getParcelableArrayList("stemsList");


                this.filePath = getArguments().getString("filePath");
                for (int i = 0; i < stemsList.size(); i++) {
                    switch (stemsList.get(i).getKey()) {
                        case "text":
                            content = stemsList.get(i).getValue();
                            break;
                        case "audio_url":
                            playUrl = stemsList.get(i).getValue();
                            break;
                        case "img_url":
                            coverImg = stemsList.get(i).getValue();
                            break;
                    }
                }

            }


        }

    }

    /**
     *
     */
    public interface OnGrammarListenChooseListener {
        // TODO: Update argument type and name
        void onGrammarListenChoose(boolean isDO, int totalNum, String title);
    }

    List<CartoonStudentSubjectiveDataBean.StemsListBean> realeaseList;
    String speakingPackageId;
    boolean isLocal = false;
    boolean isRealease = false;

//    public CartoonWordSpeakFragment(boolean isRealease, boolean isLocal, String filePath, List<CartoonStudentSubjectiveDataBean.StemsListBean> stemsList) {
//        this.isLocal = isLocal;
//        this.isRealease = isRealease;
//        this.realeaseList = stemsList;
//        this.filePath = filePath;
//        for (int i = 0; i < stemsList.size(); i++) {
//            switch (stemsList.get(i).getKey()) {
//                case "text":
//                    content = stemsList.get(i).getValue();
//                    break;
//                case "audio_url":
//                    playUrl = stemsList.get(i).getValue();
//                    break;
//                case "img_url":
//                    coverImg = stemsList.get(i).getValue();
//                    break;
//            }
//        }
//    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_cartoon_pic_speak, container, false);
        ButterKnife.bind(this, rootView);
        if (isLocal || isRealease) {
            recordAudio.setVisibility(View.INVISIBLE);
            playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.default_add));
        }

        textContent.setText(content);
        simpleDraweeView.setImageURI(coverImg);

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();


        if (getActivity() instanceof EveryDayWorkActivity) {
            totalTv.setText("/" + ((EveryDayWorkActivity) getActivity()).getTotalNum() + "");

            completeTv.setText(((EveryDayWorkActivity) getActivity()).getCompeleteNum() + "");
        }

        if (isLocal) {
            playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
        } else if (isRealease) {
            playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
        } else {
            if (!TextUtils.isEmpty(filePath) && new File(filePath).exists()) {
                if (playRecord != null) {
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                }
            }
        }

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (!isVisibleToUser) {
            resetMedio();
        } else {

            if (completeTv != null) {

                if (getActivity() instanceof EveryDayWorkActivity) {
                    completeTv.setText(((EveryDayWorkActivity) getActivity()).completeNum + "");
                }

            }

        }
        super.setUserVisibleHint(isVisibleToUser);

        LogUtil.MyLog("onDestroy", "====setUserVisibleHint=====" + isVisibleToUser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.MyLog("onDestroy", "====onDestroy=====");
        try {
            stopMedio();
        } catch (Exception e) {

        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        LogUtil.MyLog("onDestroy", "====onDestroyView=====");
        stopMedio();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        LogUtil.MyLog("onDestroy", "====onHiddenChanged=====");
    }

    @OnClick({R.id.play_audio, R.id.record_audio, R.id.play_record, R.id.simpleDraweeView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.play_audio:
                pauseRecorderUi();
                pausePlayRecord();
                playAudio();
                break;
            case R.id.record_audio:
                pausePlayRecord();
                pauseAudio();
                changeRecordUi();
                break;
            case R.id.play_record:
                pauseRecorderUi();
                pauseAudio();
                playOrPauseRecord();
                break;

        }
    }


    public static String getExceptionAllinformation(Exception ex) {
        String sOut = "";
        StackTraceElement[] trace = ex.getStackTrace();
        for (StackTraceElement s : trace) {
            sOut += "\tat " + s + "\r\n";
        }
        return sOut;
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtil.MyLog("onDestroy", "====onHiddenChanged=====");
        resetMedio();

        filePath = "";
    }

    /**
     * 播放单词
     */
    private void playAudio() {
        if (audioPlayer != null) {
            if (audioPlayer.isPlaying()) {
                pauseAudio();
            } else {
                audioPlayer.playUrl(playUrl);
            }
        } else {
            audioPlayer = new MAudioPlayer();
            audioPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
                @Override
                public void playerPause() {

                }

                @Override
                public void playerCompletion(MediaPlayer mp) {
                }

                @Override
                public void playerPrepared(MediaPlayer mp) {
                    audioPlayer.play();
                }

                @Override
                public void playerStart() {
                }

                @Override
                public void playerError(MediaPlayer mp, int what, int extra) {
                }
            });
            audioPlayer.playUrl(playUrl);
        }

    }

    /**
     * 暂停单词
     */
    private void pauseAudio() {
//        String urlPath = "res://" + getActivity().getPackage() + "/" + R.mipmap.cartoon_voice_icon;
//        playAudio.setImageURI(urlPath);
        if (audioPlayer != null) {
            audioPlayer.pause();
        }

    }

    /**
     * 停止播放单词
     */
    private void stopAudio() {
        if (audioPlayer != null) {
            audioPlayer.stop();
        }
    }


    String filePath;

    /**
     * 录音
     */
    MP3Recorder mRecorder;
    /**
     * 录音  播放
     */
    MAudioPlayer recordPlayer;

    String recorderName = "";

    /**
     * 开始 录音
     */
    private void resolveRecord() {
        if (filePath != null) {
            FileUtils.deleteFile(filePath);
        }
        filePath = cachDir;
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(getActivity(), "创建文件夹失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        recorderName = resId + Constant.DIVID_CODE + DataUtil.getCurTimeByFormat("yyyy-MM-dd") + ".mp3";
        filePath = cachDir + recorderName;

        mRecorder = new MP3Recorder(new File(filePath));

        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    resolveError();
                }
            }
        });

        startRecorderUi();
    }

    /**
     * 录音状态改变
     */
    private void changeRecordUi() {
        if (mRecorder != null) {
            if (mRecorder.isRecording()) {
                LogUtil.MyLog("mRcorder", "=======暂停录音=====");
                pauseRecorderUi();
            } else {
                LogUtil.MyLog("mRecorder", "=======继续录音=====");
                resolveRecord();
            }

        } else {
            resolveRecord();
        }

//
    }

    /**
     * 录音异常
     */
    private void resolveError() {
        FileUtils.deleteFile(filePath);
        filePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
        }
    }

    /**
     * 开始录音ui
     */
    private void startRecorderUi() {
        try {
            startRecord = System.currentTimeMillis();
            isRecoeder = true;
            mRecorder.start();

            String urlPath = "res://com.fancy.learncenter/" + R.mipmap.cartoon_record_g_icon;
            DraweeController draweeController =
                    Fresco.newDraweeControllerBuilder()
                            .setUri(urlPath)
                            .setOldController(recordAudio.getController())
                            .setAutoPlayAnimations(true) // 设置加载图片完成后是否直接进行播放
                            .build();
            recordAudio.setController(draweeController);

            playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
            if (getActivity() instanceof EveryDayWorkActivity) {
                ((EveryDayWorkActivity) getActivity()).changeUi(true);
            }

        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.MyLog("mRecorder", "======mRecorder=====" + e);
            Toast.makeText(getActivity(), "录音出现异常，请重试", Toast.LENGTH_SHORT).show();
            resolveError();
            startRecord = 0;
            endRecord = 0;
            pauseRecorderUi();
            return;
        }
    }


    boolean isRecoeder = false;

    long startRecord = 0;
    long endRecord = 0;

    /**
     * 停止录音ui
     */
    private void pauseRecorderUi() {
        endRecord = System.currentTimeMillis();
        long recorderDur = endRecord - startRecord;
        startRecord = 0;

        if (isRecoeder) {
            saveLoacal(recorderDur);
        }


        if (mRecorder != null) {
            mRecorder.stop();
        }
        if (recordAudio != null) {
            recordAudio.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_record_icon));
        }
    }

    /**
     * 暂停播放录音资源
     */
    private void pausePlayRecord() {
        if (recordPlayer != null) {
            recordPlayer.pause();
        }
    }


    /**
     * 暂停播放录音资源
     */
    private void stopPlayRecord() {
        if (recordPlayer != null) {
            recordPlayer.stop();
        }

    }

    /**
     * 播放或者暂停 录音音频
     */
    private void playOrPauseRecord() {

        if (isLocal) {
            if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
                ToastUtil.show("小朋友，本地录音破损，");
                return;
            }

        } else if (isRealease) {

        } else {
            if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
                ToastUtil.show("小朋友，请先录制单词吧");
                return;
            }
        }


        if (recordPlayer != null) {
            if (recordPlayer.isPlaying()) {
                recordPlayer.pause();
            } else {
                recordPlayer.playUrl(filePath);
            }
        } else {
            recordPlayer = new MAudioPlayer();
            recordPlayer.setAudioPlayerStatus(new MAudioPlayer.AudioPlayerStatus() {
                @Override
                public void playerPause() {
                    if (playRecord != null) {
                        playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                    }
                }

                @Override
                public void playerCompletion(MediaPlayer mp) {
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                }

                @Override
                public void playerPrepared(MediaPlayer mp) {
                    recordPlayer.play();
                }

                @Override
                public void playerStart() {
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_play_icon));
                }

                @Override
                public void playerError(MediaPlayer mp, int what, int extra) {
                    playRecord.setImageURI(Uri.parse("res://com.fancy.learncenter/" + R.mipmap.cartoon_pause_cion));
                }
            });
            recordPlayer.playUrl(filePath);
        }

    }


    private void resetMedio() {

        pauseRecorderUi();

        pausePlayRecord();

        pauseAudio();
    }


    private void stopMedio() {
        pauseRecorderUi();

        stopAudio();

        stopPlayRecord();
    }

    boolean isSubmit = false;


    @Override
    public void fmCallBack() {
        submitData();
    }

    @Override
    public String fmCallBackValue() {
        return null;
    }

    @Override
    public String fmCallBackName() {
        return null;
    }

    private void submitData() {

        if (isSubmit) {
            return;
        }
        Map maps = new HashMap<>();

        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        File mp3File = new File(filePath);

        if (!mp3File.exists()) {
            return;
        }
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), mp3File);

        maps.put("file\"; filename=\"" + recorderName, requestFile);

        maps.put("classId", RequestBody.create(MediaType.parse("text/plain"), MyApplication.classIDStr));

        maps.put("speakingPackageId", RequestBody.create(MediaType.parse("text/plain"), speakingPackageId));

        maps.put("subjectQuestionId", RequestBody.create(MediaType.parse("text/plain"), resId));

        maps.put("type", RequestBody.create(MediaType.parse("text/plain"), "1" + ""));

        HttpMehtod.getInstance().submitWork(maps, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                BaseBean<CartoonSubmitDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonSubmitDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonSubmitDataBean>() {
                    @Override
                    public void success(CartoonSubmitDataBean dataBean) {
                        ToastUtil.show("上传成功");

                        isSubmit = true;

                        if (getActivity() instanceof EveryDayWorkActivity) {
                            ((EveryDayWorkActivity) getActivity()).addCompeleteNum();

                            completeTv.setText(((EveryDayWorkActivity) getActivity()).getCompeleteNum() + "");
                        }


                    }

                    @Override
                    public void fail(String errorCode) {
                        ToastUtil.show("上传失败");
                    }
                }).dealData();
            }
        });
    }


    private void saveLoacal(long duration) {
        isRecoeder = false;

        Utils.saveLocalRecorder(recorderName, resId, coverImg, questionsName, duration, System.currentTimeMillis());
//        Map resDatas;
//        String readResultStr = FileUtils.readFromSD(FileUtils.getSutendLocalRes());
//        if (!TextUtils.isEmpty(readResultStr)) {
//            resDatas = Utils.transStringToMap(readResultStr);
//        } else {
//            resDatas = new HashMap();
//        }
//
//        if (TextUtils.isEmpty(coverImg)) {
//            coverImg = " ";
//        }
//        if (TextUtils.isEmpty(content)) {
//            content = " ";
//        }
//        String res = coverImg + "&&" + questionsName + "&&" + duration + "&&" + DataUtil.getDateTime(endTime, "yyyy-MM-dd HH:mm:ss") + "&&" + resId;
//        resDatas.put(recorderName + "", res);
//
//        String resource = Utils.transMapToString(resDatas);
//
//        FileUtils.saveStringToFile(FileUtils.getSutendLocalRes(), resource);
    }
}
